package com.symaster.gameengine.e2d.input;

import com.symaster.gameengine.core.Component;
import com.symaster.gameengine.core.FrameCall;
import com.symaster.gameengine.geom.Vector;
import org.lwjgl.glfw.GLFW;

/**
 * 将键盘的wasd输入转换成向量
 *
 * @author yinmiao
 * @since 2024/9/15
 */
public class Keyboard extends Component implements FrameCall {

    private static final int floatCache_X = 0, floatCache_Y = 1;
    private final float[] floatCache = new float[2];
    private final Vector input = new Vector();

    public Vector getInput() {
        return input;
    }

    @Override
    public void update(long window) {
        boolean w = GLFW.glfwGetKey(window, GLFW.GLFW_KEY_W) == GLFW.GLFW_PRESS;
        boolean a = GLFW.glfwGetKey(window, GLFW.GLFW_KEY_A) == GLFW.GLFW_PRESS;
        boolean s = GLFW.glfwGetKey(window, GLFW.GLFW_KEY_S) == GLFW.GLFW_PRESS;
        boolean d = GLFW.glfwGetKey(window, GLFW.GLFW_KEY_D) == GLFW.GLFW_PRESS;

        floatCache[floatCache_X] = 0;
        floatCache[floatCache_Y] = 0;

        if (w) {
            floatCache[floatCache_Y] += 1;
        }
        if (a) {
            floatCache[floatCache_X] -= 1;
        }
        if (s) {
            floatCache[floatCache_Y] -= 1;
        }
        if (d) {
            floatCache[floatCache_X] += 1;
        }

        input.setX(floatCache[floatCache_X]);
        input.setY(floatCache[floatCache_Y]);
    }
}
